package com.jt.www.common.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jt.www.common.service.GradeService;
import com.jt.www.dao.mapper.grade.GradeMapper;
import com.jt.www.enums.ResultEnum;
import com.jt.www.model.grade.Grade;
import com.jt.www.model.grade.vo.GradeVo;
import com.jt.www.model.reps.ResultDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class GradeServiceImpl implements GradeService {

    @Autowired
    private GradeMapper gradeMapper;

    @Override
    public Integer insertGradeInfo(Grade grade) {
        if (grade == null) {
            return -1;
        }
        Grade tempGrade = gradeMapper.selectOne(grade);
        if (tempGrade != null) {
            //要添加的年级已经存在
            return -2;
        }
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        grade.setCreationTime(dateFormat.format(date));
        grade.setIsDeleted(false);
        int num = gradeMapper.insert(grade);
        return num;
    }


    @Override
    public Integer updateGradeInfo(Grade grade) {
        if (grade == null) {
            return -1;
        }
        int num = gradeMapper.updateByPrimaryKeySelective(grade);

        return num;
    }


    @Override
    public int deleteGradeById(Integer id) {
        Grade grade = new Grade();
        grade.setId(Long.valueOf(id));
        grade.setIsDeleted(true);

        int num = gradeMapper.updateByPrimaryKeySelective(grade);

        return num;
    }

    @Override
    public ResultDTO searchGradeByNameNumber(GradeVo grade) {
        if (grade.getPage() != null && grade.getRows() != null) {
            PageHelper.startPage(grade.getPage(), grade.getRows());
        }

        // 第一步 先查订单 再查 list
        List<Grade> resultList = gradeMapper.queryGrade(grade);
        for (Grade gr : resultList) {
            gr.setCreationTime(gr.getCreationTime().substring(0, 19));
        }
        PageInfo pageinfo = new PageInfo(resultList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageCount", pageinfo.getTotal());
        map.put("result", resultList);

        return new ResultDTO(ResultEnum.SUCCESS, map);
    }

}
